import { type Ref, ref } from 'vue'

import { dictApi } from '@/apis'
import { TableRefHook, useDialog } from '@/hooks'
import { getColumnDataForUpdate } from '@/utils'

import { useDictDataForm } from '.'

type Params = {
  tableRefHook: TableRefHook
}

export function useOperation({ tableRefHook }: Params) {
  const selectedId = ref('')

  const { showConfirm } = useDialog()
  const {
    show: showEdit,
    loading: editLoading,
    formModel: editFormModel,
    formRef: editFormRef
  } = useDictDataForm()

  function handleShowEdit(item: any) {
    const { dictCode, ...rest } = item

    selectedId.value = dictCode
    Object.assign(editFormModel.value, getColumnDataForUpdate(rest))
    showEdit.value = true
  }

  function handleCloseEdit() {
    showEdit.value = false
  }

  function handleEdit() {
    editFormRef.validate().then(async () => {
      try {
        editLoading.value = true

        await dictApi.updateDictData(selectedId.value, editFormModel.value)

        editLoading.value = false
        handleCloseEdit()
        tableRefHook.refresh()
      } catch {
        editLoading.value = false
      }
    })
  }

  function handleDelete(id: string) {
    showConfirm({
      content: '确认删除？',
      onOk: async () => {
        await dictApi.deleteDictData({
          ids: [id]
        })

        tableRefHook.refresh()
      }
    })
  }

  return {
    showEdit,
    editLoading,
    editFormModel,
    editFormRef,
    handleShowEdit,
    handleCloseEdit,
    handleEdit,
    handleDelete
  }
}
